package com.heima.article;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.mapper.ArticleContentMapper;
import com.heima.article.mapper.ArticleMapper;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class test {
    @Autowired
    private Configuration configuration;
    @Autowired
    ArticleContentMapper contentMapper;
    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    FileStorageService fileStorageService;

    @Test
    public void test() throws Exception {
        List<ApArticle> apArticles = articleMapper.selectList(null);
        Template template = configuration.getTemplate("article.ftl");
        apArticles.forEach(s->{
            LambdaQueryWrapper<ApArticleContent> lqw = new LambdaQueryWrapper();
            lqw.eq(ApArticleContent::getArticleId,s.getId());
            ApArticleContent apArticleContent = contentMapper.selectOne(lqw);
            if(apArticleContent == null){
                return;
            }
            StringWriter out = new StringWriter();
            Map<String, Object> params = new HashMap<>();
            params.put("content", JSONArray.parseArray(apArticleContent.getContent()));
            try {
                template.process(params,out);
            } catch (TemplateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            InputStream is = new ByteArrayInputStream(out.toString().getBytes());

            //3.把html文件上传到minio中
            String path = fileStorageService.uploadHtmlFile("", apArticleContent.getArticleId() + ".html", is);

            //4.修改ap_article表，保存static_url字段
            ApArticle article = new ApArticle();
            article.setId(apArticleContent.getArticleId());
            article.setStaticUrl(path);
            articleMapper.updateById(article);


        });


    }

}
